/**
 * 
 */
package top.jle.wx.proxy.api;



import com.alibaba.fastjson2.JSONObject;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Getter;
import lombok.Setter;
import top.jle.jpa.basic.exception.BasicCustomException;
import top.jle.jpa.basic.exception.BasicExceptionCode;

import java.io.Serial;
import java.io.Serializable;
import java.util.Optional;

/**
 * @author jim.lee
 *
 */
@Schema(title="返回信息")
@Getter
@Setter
public class ResponseBack<T> implements Serializable{
	
	private static final String SUCCESS_CODE = "ok";
	/**
	 * 
	 */
	@Serial
	private static final long serialVersionUID = -5700125269437239109L;
	@Schema(title="是否成功")
	private Boolean success;
	@Schema(title="状态码")
	private String code;
	@Schema(title="返回结果")
	private T result;
	
	/* 成功处理 */ 
	public static <T> ResponseBack<T> success(T t) {
		return new ResponseBack<>("ok", t);
	}

	public ResponseBack() {

	}

	private ResponseBack(String code, T result) {
		this.code = code;
		this.result = result;
		this.success = this.checkIsSuccess();
	}

	private Boolean checkIsSuccess() {
		return this.code.equals(SUCCESS_CODE);
	}


	public static <T> ResponseBack<T> error(BasicCustomException e) {
		return new ResponseBack<>(e);
	}

	/* BasicCustomException 处理 */
	@SuppressWarnings("unchecked")
	public ResponseBack(BasicCustomException e) {
		this.code = e.getCode();
		this.result = (T) Optional.ofNullable(e.getExtension()).orElseGet(JSONObject::new).getString("name");
		this.success = this.checkIsSuccess();
	}
	/* Exception处理 */ 
	public static <T> ResponseBack<T> error(Exception e) {
		return new ResponseBack<>(e);
	}

	public ResponseBack(Exception e) {
		this.code = BasicExceptionCode.SERVER_ERROR.getCode();
		this.result = null;
		this.success = this.checkIsSuccess();
	}
}
